<template>
    <div class="rounded-2xl w-48 h-8 bg-[var(--inputBg)] py-1 pl-2 aaaa">
        <i class="iconfont icon-search align-middle text-slate-300 ml-2"></i>
        <input @keyup.enter="searchMusic" v-model="searchText" ref="searchInput" @focus="isFocus = true"
            @blur="isFocus = false" type="text" :placeholder="placeholder"
            class="bg-[var(--inputBg)] w-36 pl-1 ml-1 focus:outline-none text-[var(--iconBg)] text-sm">
    </div>
    <div v-if="isFocus"
        class="w-96 h-[30rem] shadow-lg flex flex-col py-3  bg-[var(--active)] rounded-lg fixed top-16 left-60 z-50 overflow-auto no-scrollbar">
        <!-- 搜索历史 -->
        <div v-if="History" class="px-4">
            <div class="flex">
                <span class="text-[var(--iconBg)] pl-1">搜索历史</span>
                <div @mousedown="clearHistory">
                    <el-icon class="align-middle mb-[1.5px] ml-2 cursor-pointer">
                        <DeleteFilled class="text-[var(--iconBg)] hover:cursor-pointer" />
                    </el-icon>
                </div>
            </div>
            <!-- 历史记录详情 -->
            <div class="flex flex-wrap justify-start mb-4">
                <el-tag @mousedown="tagClick" type="info"  @close="handleClose(index)" @click="tagValue(item)"
                    v-for="( item, index ) in  searchArr " :key="item"  closable
                    class="ml-1 mt-3 hover:cursor-pointer" effect="light" round>
                    {{ item }}
                </el-tag>
            </div>
        </div>
        <!-- 热搜榜 -->
        <ul class="w-full">
            <p class="text-[var(--iconBg)] px-4 pb-2">热搜榜</p>
            <li @mousedown="songDetail(item)" ref="liStyle" v-for="( item, index ) in  hotSearchList "
                class="flex hover:bg-[var(--inputBg)] duration-300 p-4 cursor-pointer h-16">
                <p class="text-slate-500 text-xl min-w-[25px]">{{ index + 1 }}</p>
                <h6
                    class="text-[var(--iconBg)] font-bold align-bottom ml-3 mr-2 max-w-[14rem] line-clamp-1 text-ellipsis">
                    {{
            item.searchWord }}
                </h6>
                <div class="flex pt-1">
                    <span class="text-slate-500 text-xs">{{ item.score }}</span>
                    <img class="w-1/2 h-1/2 object-contain" v-if="item.iconUrl !== null" :src="item.iconUrl" alt="">
                </div>
            </li>
        </ul>
    </div>
</template>

<script setup lang='ts'>
import { ref, onMounted, watch } from 'vue'
import { DeleteFilled } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useStore } from '@renderer/store'
const { ipcRenderer } = require('electron')
const { hotSearch } = useStore()
import { storeToRefs } from 'pinia'
const { hotSearchList } = storeToRefs(hotSearch)
import { useRouter } from 'vue-router'
const router = useRouter()
const liStyle = ref<HTMLUListElement>()
const searchArr = ref<Array<string>>(JSON.parse(localStorage.getItem('search') as string) || [])
const History = ref<boolean>(true)
const searchText = ref('')
let isFocus = ref<boolean>(false)
let placeholder = ref<string>('')
const searchInput = ref<HTMLInputElement>()
onMounted(async () => {
    hotSearch.getHotSearchList()
    let res = await ipcRenderer.invoke('searchDefault')
    placeholder.value = res.body.data.showKeyword
})
watch(searchArr.value, () => {
    if (searchArr.value.length == 0) {
        History.value = false
    } else {
        History.value = true
    }
}, {
    immediate: true
})
// 删除全部搜索历史
const clearHistory = (event: Event) => {
    event.preventDefault()
    ElMessageBox.confirm(
        '确定删除全部历史记录?',
        'Warning',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            center: true
        }
    )
        .then(() => {
            localStorage.removeItem('search')
            ElMessage({
                type: 'success',
                message: '删除成功',
            })
            searchArr.value = []
            searchText.value = ''
            History.value = false
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消操作',
            })
        })
}
// 阻止默认事件
const songDetail = (item) => {
    if (searchArr.value.includes(item.searchWord)) {
    }
    else {
        searchArr.value.push(item.searchWord)
        localStorage.setItem('search', JSON.stringify(searchArr.value));
    }
    router.push({ name: 'searchMusic', query: { name: item.searchWord } })
    searchText.value = item.searchWord
    searchInput.value?.blur()
}
// 阻止默认事件
const tagClick = (event: Event) => {
    event.preventDefault()
}
// tag标签删除
const handleClose = (index: number) => {
    searchArr.value.splice(index, 1)
    localStorage.removeItem('search')
    localStorage.setItem('search', JSON.stringify(searchArr.value));
    if (searchArr.value.length == 0) {
        History.value = false
    }
}
// tag标签点击
const tagValue = (value: string) => {
    router.push({ name: 'searchMusic', query: { name: value } })
    isFocus.value = false
    searchInput.value?.blur()
    searchText.value = value
}
// 搜索回车回调
const searchMusic = () => {
    if (searchArr.value.includes(searchText.value.trim() || placeholder.value)) {
    }
    else {
        searchArr.value.push(searchText.value.trim() !== '' ? searchText.value.trim() : placeholder.value)
        localStorage.setItem('search', JSON.stringify(searchArr.value));
    }
    router.push({ name: 'searchMusic', query: { name: searchText.value.trim() !== '' ? searchText.value.trim() : placeholder.value } })
    searchText.value.trim() === '' ? searchText.value = placeholder.value : searchText.value
    searchInput.value?.blur()
    if (searchArr.value.length !== 0) {
        History.value = true
    }
}
</script>
<style scoped lang='less'>
li:nth-child(-n+4)>p {
    color: red;
}

div {
    -webkit-app-region: no-drag;
}
</style>